/* typehints:start */
import { GameRoot } from "./root";
/* typehints:end */

import { globalConfig } from "../config/global";
import { createLogger } from "../core/utils/logging";

const logger = createLogger('game/time');

/**
 * 多少毫秒算一天
 * @returns 
 */
export const getDayTime = () => {
  return globalConfig.dayMsTime || 1000;
}

export const getMonthTime = () => {
  return getDayTime() * 30;
}

export const getYearTime = () => {
  return getMonthTime() * 12;
}

export const getTimeToDay = time => {
  return time / getDayTime();
}

export class Time{
  constructor(root){
    /** @type {GameRoot} */
    this.root = root;

    // 游戏正常无暂停运行时长
    this.runTime = 0;

    // fps
    this.fps = 0;

    this.tasks = {};
  }

  update(dt){
    this.runTime += dt;

    this.run('world_time', () => {
      if(this.root.gamePlay){
        this.root.worldData.time += getDayTime() / 1000;
      }
    }, getDayTime());

    // 一个月更新一次
    // this.run('savegame', () => {
    //   logger.log('⏰ 定时保存:', this.getCurrentDateDesc());
    //   this.root.saveWorldData();
    //   this.root.saveItemData();
    // }, getMonthTime());

    if(globalConfig.debug.disableFpsLog){
      this.fps++;

      this.run('fps-update', () => {
        logger.log('fps: ', this.fps);
        this.fps = 0;
      }, 1000, true)
    }
  }

  getCurrentDateDesc(){
    let year = this.getYear();
    let month = this.getMonth();
    let day = this.getDay();
    let season = this.getSeason();

    return `${year}年${month}月${day}日 [${season}]`;
  }

  getYear(){
    let time = this.root.worldData.time * 1000;

    return ~~(time / getYearTime());
  }

  getMonth(){
    let time = this.root.worldData.time * 1000;

    return ~~((time % getYearTime()) / getMonthTime()) + 1;
  }

  getDay(){
    let time = this.root.worldData.time * 1000;
    
    return ~~((time % getMonthTime()) / getDayTime()) + 1;
  }

  getSeason(){
    return ['春', '夏', '秋', '冬'][this.getYear() % 4]
  }

  /**
   * 
   * @param {*} name 任务名称
   * @param {*} cb 任务回调
   * @param {*} time 任务定时
   * @param {*} delay 是否延迟执行
   * @param {Boolean} only 是否只执行一次
   */
  run(name, cb, time, delay = true, only = false){
    if(!this.tasks[name]){
      this.tasks[name] = {
        time,
        lastTime: delay ? this.runTime : -time
      }
    }

    const now = this.runTime;
    if(now - this.tasks[name].lastTime >= time && !this.tasks[name].only){
      this.tasks[name].lastTime = now;

      if(only) this.tasks[name].only = true;

      cb();
    }
  }

  /**
   * 获取任务下次执行时间
   */
  getRunTime(key){
    let task = this.tasks[key];

    if(task){
      let time = task.time - (this.runTime - task.lastTime);
      return isNaN(time) ? 999 : time;
    } else {
      return false;
    }
  }
}